﻿/** String utilities****/
function encode(decodedString) {
    return encodeURIComponent(decodedString);
}

function decode(encodedString) {
    return decodeURIComponent(encodedString.replace(/\+/g, " "));
}

String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }

/****Helper methods*****/
function GetCookie(name) {
    var cname = name + "=";
    var dc = document.cookie;
    if (dc.length > 0) {

        begin = dc.indexOf(cname);
        if (begin != -1) {
            begin += cname.length;
            end = dc.indexOf(";", begin);
            if (end == -1) end = dc.length;
            return unescape(dc.substring(begin, end)); // changed as per req: Aswin
            //return unescape(dc.substring(begin, end).split("=")[1]);
        }
    }
    return null;
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return '';
}

function xreplace(checkMe, toberep, repwith) {
    var temp = checkMe;
    var i = temp.indexOf(toberep);
    while (i > -1) {
        temp = temp.replace(toberep, repwith);
        i = temp.indexOf(toberep);
    }
    return temp;
}

function getHostPath() {
    if (location.href.indexOf('localhost') > -1) {
        return "localhost:2081";
        //return "wac.213e.edgecastcdn.net/00213E/v1_56";
    }
    else if (location.href.indexOf('dev') > -1) {
        return "dev.blog.cmlmediasoft.com";
    }
    else {
        return "test.blog.cmlmediasoft.com";
    }
}
function getLoadingImagePath() {
    return 'http://' + getHostPath() + '/Images/loading.gif';

}

//   function
function createCookie(name, value, expires, path, domain, secure) {

    document.cookie = name + "=" + escape(value) +
	((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
	((path == null) ? "" : "; path=" + path) +
	((domain == null) ? "" : "; domain=" + domain) +
	((secure == null) ? "" : "; secure");

}

function deleteCookie(name, path, domain) {

    var expDate = new Date();
    expDate.setTime(expDate.getTime());
    if (GetCookie(name)) {
        document.cookie = name + "=" + escape(GetCookie(name)) +
	    ((path == null) ? "" : "; path=" + path) +
	    ((domain == null) ? "" : "; domain=" + domain) +
	    "; expires=" + expDate.toGMTString();
    }
}


function AddLoadingGif(container, opts) {
    var e = container;
    var zIndex = 100000;
    if (!$.isEmptyObject(opts)) {
        zIndex = (typeof opts.zindex == 'undefined') ? 100000 : opts.zindex;
    }
    var overlay = $("<div id='ol' style='opacity:0.3;filter:alpha(opacity=30);position:absolute;z-index:100000;top:0px;left:0px;width:100%;height:100%;'></div>");
    var xtop = $(e).height() / 2 - 30;
    var xleft = $(e).width() / 2 - 30;
    var imgPath = getLoadingImagePath();
    var overlay2 = $("<div style='position:absolute;top:" + xtop + "px;left:" + xleft + "px;'></div>");
    var loadingIMG = $("<img src='" + imgPath + "' style='width:50px;height:50px;position:absolute;' />");
    $(overlay2).append(loadingIMG);
    $(overlay).append(overlay2);
    $(e).append(overlay);
}

function RemoveLoadingGif(container, opts) {
    if (container != null) {
        var e = container;
        $(e).remove('#ol');
        //$('div').remove('#ol');
    }
}


/*  generic method to GetArray from string-- aswin.samuel  
rawString--string to convert to object or array
*/
function GetArray(rawString) {
    return jQuery.parseJSON(rawString);
}
var browser = "";
function submitButton(e, but) {
    var characterCode;
    if (!e)
        e = window.event;
    if (e && e.which) {
        e = e;
        characterCode = e.which;
    }
    else {
        e = event;
        characterCode = e.keyCode;
    }

    if (characterCode == 13) {

        if (browser == 'IE') {
            if (but != null) {
                try {
                    but.onclick();
                } catch (e) { if (e.name == "TypeError") eval(but.onclick); }
            }
        }
        else {
            if (but != null) {
                if (but.value == undefined) {
                    //but.onclick();
                    $(but).click();
                }
                else {

                    but.click();
                }
            }

        }


        return false;
    }
    else {
        return true;
    }
}

function ValidateURL(currentURL) {
    if (currentURL.length != 0) {
        if (!/^(www?):\/\//i.test(currentURL)) {
            currentURL = (currentURL.indexOf('http://') > -1) || (currentURL.indexOf('https://') > -1) ? currentURL.replace("http://", "").replace("https://", "").replace('www.', "") : currentURL.replace('www.', "");
            currentURL = 'www.' + currentURL; // set both the currentURLue

        }
        if (!/^(https?|ftp):\/\//i.test(currentURL)) {
            currentURL = 'http://' + currentURL;
        }
        return currentURL;
    }
}

/*
opts.url
opts.params
opts.container-->loadinggif container
opts.mtype-->get or post
opts.callback--> call back method
opts.datatye-->html,json
*/
var objAjax = null;
function MakeJAjaxCall(opts) {
    //    if (objAjax != null) {
    //        objAjax.abort();
    //    }
    var callType = (typeof opts.calltype != 'undefined') ? opts.calltype : 'get';
    var dataType = (typeof opts.datatype != 'undefined') ? opts.datatype : 'html';
    var params = (typeof opts.params != 'undefined') ? opts.params : null;
    var isLodingGif = (typeof opts.isLoadingGif != 'undefined') ? opts.isLoadingGif : true;
    var container = (typeof opts.container != 'undefined') ? opts.container : $('body');

    var callback = (typeof opts.onsuccess != 'undefined' && typeof opts.onsuccess == 'function') ? opts.onsuccess : function () { void (0) };
    var fnFail = (typeof opts.onfailure != 'undefined' && typeof opts.onfailure == 'function') ? opts.onfailure : function () { void (0) };

    if (isLodingGif)
        AddLoadingGif(container, null);
    objAjax = $.ajax({
        type: callType,
        url: opts.url,
        datatype: dataType,
        data: params,
        error: function (request, error) { //alert(error);
        },
        success: function (data) {
            if (isLodingGif) {
                RemoveLoadingGif(container, opts)

            }
            callback(data, opts);
            objAjax = null;
            isScrolled = null;
        }
    });
}

/* 
Note:   created to resolve the json call in Chrome. the error in Chrome is fixed, however failed to resolve the error in IE. Suspect the ie issue to be due to the
cross domain ajax call. To be checked later. Dipin Kumar
*/
function MakeJSONCall(opts) {
    if (objAjax != null) {
        //objAjax.abort();
    }
    var callType = (typeof opts.calltype != 'undefined') ? opts.calltype : 'get';
    var dataType = (typeof opts.datatype != 'undefined') ? opts.datatype : 'html';
    var params = (typeof opts.params != 'undefined') ? opts.params : null;
    var isLodingGif = (typeof opts.isLoadingGif != 'undefined') ? opts.isLoadingGif : true;
    var container = (typeof opts.container != 'undefined') ? opts.container : $('body');
    var callback = (typeof opts.onsuccess != 'undefined' && typeof opts.onsuccess == 'function') ? opts.onsuccess : function () { void (0) };
    var fnFail = (typeof opts.onfailure != 'undefined' && typeof opts.onfailure == 'function') ? opts.onfailure : function () { void (0) };
    if (isLodingGif)
        AddLoadingGif(container, null);
    objAjax = $.ajax({
        type: callType,
        url: opts.url,
        beforeSend: function (x) {
            if (x && x.overrideMimeType) {
                x.overrideMimeType("application/j-son;charset=UTF-8");
            }
        },
        datatype: dataType,
        data: params,
        error: function (request, error) { //alert(error);
        },
        success: function (data) {
            if (isLodingGif) {
                RemoveLoadingGif(container, opts)
            }
            callback(data, opts);
            objAjax = null;
            isScrolled = null;
        }
    });
}
function GetJSONData(opts) {
    var callback = (typeof opts.onsuccess != 'undefined' && typeof opts.onsuccess == 'function') ? opts.onsuccess : function () { void (0) };
    $.getJSON(opts.url + '&callback=?', callback);
}


//opts={usrctrl:'usercontrol location path',params:'params for user control',container:'to fill data in container',onsuccess:'fn to call'}

function LoadM(opts) {
    var userControlUrl = opts.usrctrl; //
    var parms = opts.params; //
    var container = opts.container;
    var onsuccess = (typeof opts.onsuccess != 'undefined' && typeof opts.onsuccess == 'function') ? opts.onsuccess : function () { void (0) };
    var appendorinsert = (typeof opts.appendorinsert != 'undefined') ? opts.appendorinsert : 2;
    var callType = (typeof opts.calltype != 'undefined') ? opts.calltype : 'get';
    var dataType = (typeof opts.datatype != 'undefined') ? opts.datatype : 'html';

    var url = '/pages/ajax/moduleloader.aspx';
    var params = 's=' + userControlUrl + parms;

    opts = { url: url, params: params, datatype: dataType, calltype: callType, container: container, onsuccess: onCompleteLoadM, onerror: onErrorLoadM, 'oncomplete': onsuccess, appendorinsert: appendorinsert };
    MakeJAjaxCall(opts);
    //MakeJAjaxCall(_url, _params, returnDatatype, onCompleteLoadM, onErrorLoadM, callType, opts);

}


function onCompleteLoadM(response, opts) {
    response = xreplace(response, "<body>", "");
    response = xreplace(response, "</body>", "");

    response = xreplace(response, "form", "x");
    response = xreplace(response, "x_test", "form");
    response = xreplace(response, "_VIEWSTATE", "sx");

    if (opts.appendorinsert != null) {
        if (opts.appendorinsert == 2) {
            $(opts.container).text("");
            $(opts.container).html(response);
        }
        else {
            $(opts.container).append(response);
        }
    }

    if (typeof (opts.oncomplete) == 'function') {
        opts.oncomplete(opts);
    }
}

function onErrorLoadM(response, opts) {
    $(opts.container).innerHTML = "<div align=center style='color:red'>Error Loading</div>"
}


/* 
Purpose      : Generalised Confirmation pop up.
Function     : genAlertPOPUP(opts);
opts example : { 'AlertText': 'Are you sure ??', 'SaveTxt': 'Save', 'CancelTxt': 'No','DSTxt':'DontSave', 'SaveClick': function () {}, 

'CancelClick': function(){},'DontSaveClick':function(){}, 'reqCancel': true};
*/

//********************************Alert pop up without Dialog call:********************************
var tabCount = 0;

function genAlertPOPUP(_opts) {
    var genPopupContainer = $("<div id='genricAlertPopup' class='BA_MainDiv'></div>");
    var genPopUpHead = $("<div id='genricPopupHead' class='Blog_PopupMasterHeader'></div>");
    $(genPopUpHead).text("Alert");
    var genPopUpBody = $("<div id='genricPopupBody' class='BAlert_Content'></div>");
    var genPopUpInnerBody = $("<div id='genricPopupInnerBody' class='BAlert_ContInner'></div>");

    var genPopUpInnerImg = $("<div id='genricPopupInnerImg' class='BAlert_ImgDiv'></div>");
    var genPopUpInnerImgSub = $("<div id='genricPopupInnerImgSub' class='BAlert_Img'></div>");
    var genPopUpInnerImgSpan = $("<div id='genricPopupInnerImgSpan' class='BAlert_Txt'></div>");
    $(genPopUpInnerImgSpan).text("Would you like to save your changes before exiting?");
    genPopUpInnerImg.append(genPopUpInnerImgSub);
    genPopUpInnerImg.append(genPopUpInnerImgSpan);

    var genPopUpInnerBtn = $("<div id='genricPopupInnerBtn' class='BAlertButtDiv'></div>");
    var genPopUpInnerBtn1 = $("<div id='genricPopupInnerBtn1' class='Grey_Button Grey_DS'></div>");
    genPopUpInnerBtn1.text("Don't Save");
    var genPopUpInnerBtn2 = $("<div id='genricPopupInnerBtn2' class='Grey_Button'></div>");
    genPopUpInnerBtn2.text("Cancel");
    var genPopUpInnerBtn3 = $("<div id='genricPopupInnerBtn3' class='Green_Button'></div>");
    genPopUpInnerBtn3.text("Save");

    genPopUpInnerBtn.append(genPopUpInnerBtn1);
    genPopUpInnerBtn.append(genPopUpInnerBtn2);
    genPopUpInnerBtn.append(genPopUpInnerBtn3);

    genPopUpInnerBody.append(genPopUpInnerImg);
    genPopUpInnerBody.append(genPopUpInnerBtn);

    genPopUpBody.append(genPopUpInnerBody);

    genPopupContainer.append(genPopUpHead);
    genPopupContainer.append(genPopUpBody);

    $(genPopUpInnerBtn1).click(function () {
        if (typeof (_opts.DontSaveClick) == "function") {
            _opts.DontSaveClick();
            fnClosePopUpWindow();
        }
    });

    $(genPopUpInnerBtn2).click(function () {
        if (typeof (_opts.CancelClick) == "function") {
            _opts.CancelClick();
            fnClosePopUpWindow();
        }
    });

    $(genPopUpInnerBtn3).click(function () {
        if (typeof (_opts.SaveClick) == "function") {
            _opts.SaveClick();
            fnClosePopUpWindow();
        }
    });

    var opts = { 'maxWidth': '445px', 'minWidth': '445px', 'minHeight': '163px', 'marginTop': '16%' };
    var toInsertDiv = fnGenDialogwithScroll(opts);
    toInsertDiv.append(genPopupContainer);

    //toInsertDiv.animate({ left: "35%" }, { queue: false, duration: 1000 });

}

$('#genricAlertPopup').keydown(function (e) {
    if (e.which == '9') {
    }
    if (e.which == '13') {
    }
});

//**********************************************End of generic Alert Pop Up*************************************************


/* 
Created By   : P K Sharath
Purpose      : Generalised Pop Up.
Function     : fnGenDialogwithScroll(opts);

example:
var opts = { 'maxWidth': '770px','maxWidth': '770px','minHeight': '770px','marginTop':'2%'};

params details:
maxWidth,maxWidth,minHeight   : size of the container div

returns the container DIV
*/
//********************************Pop Up Loader without Dialog call:********************************
function fnGenDialogwithScroll(opts) {
    if ($('#outer').length == 0) {
        var outerDiv;
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            outerDiv = $("<div id='outer' class='outerContainer' style='background-color: #A0A0A0;filter: alpha(opacity=97)'/>");
            $('body').attr({ scroll: 'no' });
        }
        else {
            outerDiv = $("<div id='outer' class='outerContainer' style='background-color: rgba(104,104,104, 0.75);filter: alpha(opacity=100)'/>");
            $('body').css({ overflow: 'hidden' });
        }
        var innerDiv = $("<div id='inner' class='innerContainer' style='margin-top:" + opts.marginTop + ";max-width:" + opts.maxWidth + ";min-width:" + opts.minWidth + ";min-height:" + opts.minHeight + ";'/>");
        outerDiv.append(innerDiv);
        $('body').append(outerDiv);
        return innerDiv;
    }
    else if ($('#outer').length == 1) {
        var outerDiv1;
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            outerDiv1 = $("<div id='outer1' class='outerContainer' style='background-color: #A0A0A0;filter: alpha(opacity=97)'/>");
            $('body').attr({ scroll: 'no' });
        }
        else {
            outerDiv1 = $("<div id='outer1' class='outerContainer' style='background-color: rgba(104,104,104, 0.75);filter: alpha(opacity=100)'/>");
            $('body').css({ overflow: 'hidden' });
        }
        var innerDiv1 = $("<div id='inner1' class='innerContainer' style='margin-top:" + opts.marginTop + ";max-width:" + opts.maxWidth + ";min-width:" + opts.minWidth + ";min-height:" + opts.minHeight + ";'/>");
        outerDiv1.append(innerDiv1);
        $('body').append(outerDiv1);
        return innerDiv1;
    }

}

function fnClosePopUpWindow() {
    if ($('#outer1').length == 1) {
        $('#outer1').remove();
    }
    else {
        $('#outer').remove();
        bringScrollforBody();
    }
}

function bringScrollforBody() {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        $("body").attr({ scroll: 'yes' });
        $("body").css({ overflow: 'inherit' });
    }
    else {
        $("body").css({ overflow: 'inherit' });
    }
}

//var KEYCODE_ESC = 27;
//$(document).keyup(function (e) {
//    if (e.which == KEYCODE_ESC) {
//        if ($('#outer').length > 0) {
//            fnClosePopUpWindow();
//        }
//    }
//});

/* Below function is Created by Khyati on 9/12/11 */
function loadSelectFromFiles(pars) {
    var opts = { 'maxWidth': '882px', 'minHeight': '555px', 'marginTop': '7%' };
    var containerDiv = fnGenDialogwithScroll(opts);
    var _params = pars;
    _params += "&Blogid=" + GetCookie('bg_blogid');
    var opts = { 'usrctrl': '../../_modules/blog/ucSelectfromFiles.ascx', 'params': _params, 'container': containerDiv, 'onsuccess': onSuccessSelectFromFile }
    LoadM(opts);
}

function onSuccessSelectFromFile() {

}
function popKeepDeleteTopArrow(e, obj, params) {
    closeKeepDeleteTopArrow();
    //alert(e.pageX + "," + e.pageY);
    var btnContainer = $("<div id='keepDelContainer' class='BS_ArwTopRgt' style='top:" + e.pageY + "px;left:" + params.statLeft + "px'></div>");
    var btnKeep = $("<div class='BlackKeep_Button BS_Btn3' onclick='closeKeepDeleteTopArrow();'></div>");
    var btnDelete = $("<div class='Red_Button BS_Btn4'></div>");
    $(btnDelete).click(function () {
        if (typeof (params.fnDelete) == "function") {
            closeKeepDeleteTopArrow();
            params.fnDelete(obj);
        }
    });

    $(btnContainer).prepend(btnKeep);
    $(btnContainer).append(btnDelete);
    $('body').append(btnContainer);
}
function closeKeepDeleteTopArrow() {
    $('.tipsy').remove()
    if ($('#keepDelContainer') != null) {
        $('#keepDelContainer').remove();
    }
}
$(document).keydown(function (e) {
    if (e.which == '27') {
        closeKeepDeleteTopArrow();
    }
});


//args - pass the is od the container div which has the controls that are supposed to be modified.
function setInitialDataField(args) {
    var array = $('#' + args + ' input:text,:radio,:checkbox , #' + args + ' textarea , #' + args + ' select , #' + args + ' .CR_Curimg , #' + args + ' .togglebtnon , #' + args + ' .togglebtnoff');

    array.each(function () {

        switch (this.nodeName.toLowerCase()) {
            case 'select':
                $(this).data('initialValue', $(this).val());
                break;
            case 'h6':  //image uplaod change  h6 text name
                $(this).data('initialValue', $(this).text());
                break;
            case 'div': //button on off change class
                $(this).data('initialValue', $(this).attr('class'));
                break;
            case "textarea":
                if (typeof $(this).val() == 'undefined')
                { $(this).data('initialValue', ''); }
                else
                { $(this).data('initialValue', $(this).val()); }
                break;
            case "input":
                switch (this.type.toLowerCase()) {
                    case "checkbox":
                    case "radio":
                        $(this).data('initialValue', $(this).is(':checked'));
                        break;
                    default:
                        $(this).data('initialValue', $(this).val());
                        break;
                }

                break;
        }
    });
}

//args - pass the is od the container div which has the controls that are supposed to be modified.
function isDataFieldChanged(args) {

    var onchangeflag = false;
    var array = $('#' + args + ' input:text,:radio,:checkbox , #' + args + ' textarea , #' + args + ' select , #' + args + ' .CR_Curimg , #' + args + ' .togglebtnon , #' + args + ' .togglebtnoff');

    array.each(function () {
        switch (this.nodeName.toLowerCase()) {
            case 'select':
                if ($(this).data('initialValue') && $(this).data('initialValue') != $(this).val()) {
                    onchangeflag = true;
                }
                break;
            case 'h6':  //image upload tag h6 change image name 

                if ($(this).data('initialValue') != null && $(this).data('initialValue') != $(this).text()) {
                    onchangeflag = true;
                }
                break;
            case 'div':  //button on off change class
                if ($(this).data('initialValue') && $(this).data('initialValue') != $(this).attr('class')) {
                    onchangeflag = true;
                }
                break;

            case "textarea":
                if ($(this).data('initialValue') != $(this).val()) {
                    onchangeflag = true;
                }
                break;
            case "input":
                switch (this.type.toLowerCase()) {
                    case "checkbox":
                    case "radio":
                        if ($(this).data('initialValue') != null && $(this).data('initialValue') != $(this).is(':checked')) {
                            onchangeflag = true;
                        }

                        break;
                    default:
                        if ($(this).attr('mText') == "1") {
                            onchangeflag = false;
                        }
                        else {
                            if ($(this).data('initialValue') != null && $(this).data('initialValue') != $(this).val()) {
                                onchangeflag = true;
                            }
                        }
                        break;
                }

                break;
        }
    });
    return onchangeflag;
}

//Code for left panel height
$(window).resize(function () {
    fnresizeleftpanel();
});
function fnresizeleftpanel() {


    if (typeof window.innerWidth != 'undefined') {
        windowHeight = window.innerHeight;
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first
    // line in the document)
    else if (typeof document.documentElement != 'undefined'
                && typeof document.documentElement.clientWidth != 'undefined'
                && document.documentElement.clientWidth != 0) {
        windowHeight = document.documentElement.clientHeight;
    }
    // older versions of IE
    else {
        windowHeight = $('body')[0].clientHeight;
    }
    $('#Size').css({ height: windowHeight });
    var rgtHeight = $('#Size').height();
    $('#idRgtPanel').css({ height: rgtHeight });
}

function xStopPropagation(e) {
    if ((navigator.userAgent.indexOf("MSIE") > -1 && (navigator.userAgent.indexOf("MSIE 5") == -1 || navigator.userAgent.indexOf("MSIE 6") == -1) && !(navigator.userAgent.indexOf("opera") > -1))) { //IE

        if (!e) e = window.event; e.cancelBubble = true;
    }
    else {
        e.stopPropagation();
    }
}